// import User from "../model/user";
import ApiError from "../error/ApiError";
import ApiErrorNames from "../error/ApiErrorNames";
import qianchuanAdShop from "../model/qianchuanAdShop"
import shop from "../model/shop"
import DlyadminAigoods from '../model/dlyadminAigoods'
import DlyAdminUser from '../model/dlyadminuser'
import mongoose from 'mongoose'
import QianchuanBuyCodeSchema from '../model/qianchuanbuycode'
import moment from 'moment'

function getStartTimeAndEndTime(config) {
  const { timenum, selectTiemtype } = config
  console.log('configconfigconfig', config)
  // selectTiemtype 1 天 2 月 3 年
  let startTime = moment(new Date())
  const endTime = moment(new Date())
  if (selectTiemtype == 1) {
    endTime.add(timenum, 'days')
  }
  if (selectTiemtype == 2) {
    endTime.add(timenum, 'months')
  }
  if (selectTiemtype == 3) {
    endTime.add(timenum, 'years')
  }
  return {
    startTime,
    endTime: endTime,
  }
}

class QianchuanController {

  static async buyinfo(ctx) {
    console.log("参数ctx", ctx.request.query);
    const { shop_id, aavid } = ctx.request.query;
    // || !aavid 后期需要加入
    if (!shop_id) {
      ctx.body = '参数错误'
    }
    const shopData = await shop.findOne({ shop_id })
    if (!shop) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('店铺不存在')
      )
    }
    const getAuer = await qianchuanAdShop.findOne({ shopInfo: shopData._id })
    ctx.body = getAuer || {
      msg: '暂无数据'
    }
  }
  static async addcode(ctx) {

    // 限制权限
    console.log("参数ctx", ctx.request.header.jwtuserinfo.roleName);
    const roleName = ctx.request.header.jwtuserinfo.roleName
    if (!roleName && roleName !== 'admin' && roleName !== 'adminSp') {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('无权添加')
      )
    }
    const postData = ctx.request.body
    const { taocan, inputernum, proxyId } = postData
    if (!taocan || !inputernum || !proxyId) {
      ctx.body = '参数错误'
    }
    // 判断是否为mongoid
    try {
      new mongoose.Types.ObjectId(taocan)
      new mongoose.Types.ObjectId(proxyId)
    } catch (error) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('id错误')
      )
    }
    // 查询套餐
    const taocandata = await DlyadminAigoods.findOne({ _id: taocan })
    if (!taocandata) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('套餐不存在')
      )
    }
    // 查询代理
    const proxyUserInfo = await DlyAdminUser.findOne({ _id: proxyId })
    if (!proxyUserInfo) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('代理不存在')
      )
    }
    const addList = []
    for (let i = 0; i < inputernum; i++) {
      addList.push({
        goods: taocan,
        proxy: proxyId,
      })
    }
    const addData = await QianchuanBuyCodeSchema.insertMany(addList)
    ctx.body = addData.map(item => ({
      id: item._id,
      good: taocandata.name,
      price: taocandata.price,
      proxy: proxyUserInfo.userName
    }))
  }
  static async getcodeList(ctx) {
    const { proxyId, goodsId, status, page, pageSize } = ctx.request.query
    const query = {}
    if (proxyId) {
      query.proxy = proxyId
    }
    if (goodsId) {
      query.goods = goodsId
    }
    if (status) {
      query.useStatus = status
    }
    const total = await QianchuanBuyCodeSchema.count(query)
    const list = await QianchuanBuyCodeSchema
      .find(query)

      .populate('goods')
      .populate('proxy').sort({ createTime: -1 })
      .limit(pageSize * 1)
      .skip((page - 1) * pageSize)


    ctx.body = {
      list,
      total,
      page,
      pageSize
    }
  }
  static async useCodeBuy(ctx) {


    const { codeId, shopId, aavid } = JSON.parse(ctx.request.body)
    console.log('ctx.request.body', codeId, shopId, aavid)
    if (!codeId || !shopId || !aavid) {
      console.log('参数错误')
      throw new ApiError(
        ApiErrorNames.selectInDengtData('参数错误')
      )
    }
    try {
      new mongoose.Types.ObjectId(codeId)
    } catch (error) {
      console.log('error', error)
      throw new ApiError(
        ApiErrorNames.selectInDengtData('兑换码错误')
      )
    }
    const codeData = await QianchuanBuyCodeSchema.findOne({ _id: codeId })
    console.log('codeData', codeData)
    if (!codeData) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('兑换码不存在')
      )
    }
    if (codeData.useStatus) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('兑换码已使用已使用')
      )
    }
    const getShopData = await shop.findOne({
      shop_id: shopId,

      // aiUserId: payResult.order_user_id
    })
    if (!getShopData) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('店铺不存在')
      )
    }


    const getGoodInfo = await DlyadminAigoods.findOne({
      _id: codeData.goods,
      status: '1',
    })
    if (!getGoodInfo) {
      throw new ApiError(
        ApiErrorNames.selectInDengtData('商品不存在')
      )
    }

    const serverTime = getStartTimeAndEndTime(getGoodInfo)

    // 更新用户剩余时间
    const getQiancuanserver = await qianchuanAdShop.findOne({
      shopInfo: getShopData._id,
      // 后期考虑是否加入aavid
    })

    if (!getQiancuanserver) {
      await qianchuanAdShop.create({
        shopInfo: getShopData._id,
        aavid: aavid,
        service_start_time: serverTime.startTime,
        service_end_time: serverTime.endTime,
        // current_service_order_id: codeId,
      })
    } else {
      if (new Date().getTime() > getQiancuanserver.service_end_time) {
        await qianchuanAdShop.updateMany({
          shopInfo: getShopData._id,
        }, {
          $set: {
            service_end_time: serverTime.endTime,
            // current_service_order_id: getAter._id,
          }
        })
      }
      if (new Date().getTime() <= getQiancuanserver.service_end_time) {
        const { timenum, selectTiemtype } = getGoodInfo
        // if (selectTiemtype == '1') {
        // 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
        // }
        // if (selectTiemtype == '2') {
        // 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
        // }
        // if (selectTiemtype == '3') {
        // 	getQiancuanserver.service_end_time = moment(getQiancuanserver.service_end_time).add(timenum, 'year')


        // }
        // getQiancuanserver.save()
        let endtime = getQiancuanserver.service_end_time
        if (selectTiemtype == '1') {
          endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'day')
        }
        if (selectTiemtype == '2') {
          endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'month')
        }
        if (selectTiemtype == '3') {
          endtime = moment(getQiancuanserver.service_end_time).add(timenum, 'year')
        }
        await qianchuanAdShop.updateMany({
          shopInfo: getShopData._id,
        }, {
          $set: {
            service_end_time: endtime,
            // current_service_order_id: getAter._id,
          }
        })
      }
    }


    codeData.useStatus = 1
    codeData.useShop = getShopData._id
    codeData.useTime = new Date()
    codeData.useAdId = aavid
    await codeData.save()
    ctx.body = {
      msg: '兑换成功'
    }

  }

}

export default QianchuanController